import React from "react";
import "bootstrap/dist/css/bootstrap.css";
export default class ComList extends React.Component {
  constructor() {
    super();
    this.state = {
      CommentList: []
    };
  }
  componentWillMount() {
    this.getCarList();
  }
  render() {
    return (
      <div>
        <div id="app">
          <div className="panel panel-primary">
            <div className="panel-heading">
              <h3 className="panel-title">汽车列表</h3>
            </div>
            <div className="panel-body">
              <form className="form-inline">
                <div className="form-group">
                  <label htmlFor="exampleInputPassword1">汽车名称</label>
                  <input type="text" className="form-control" ref="carName" />
                </div>
                <button
                  className="btn btn-primary"
                  onClick={() => this.addCar()}
                >
                  添加
                </button>
              </form>
            </div>
          </div>
          <table className="table table-hover table-striped table-bordered">
            <thead>
              <tr>
                <th>编号</th>
                <th>汽车名称</th>
                <th>创建时间</th>
                <th>更多操作</th>
              </tr>
            </thead>
            <tbody>
              {this.state.CommentList.map(item => {
                return (
                  <tr key={item.id}>
                    <td>{item.id}</td>
                    <td>{item.name}</td>
                    <td>{item.ctime}</td>
                    <td>
                      {/* <a href="#"></a> */}
                      <button
                        type="button"
                        className="btn btn-success"
                        onClick={() => this.deleteCar(item.id)}
                      >
                        删除
                      </button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>
    );
  }
  // 使用 async 和 await 同步 请求数据
  getCarList = async () => {
    const { data } = await this.$http.get("/getcarlist");
    this.setState({
      CommentList: data.result
    });
  };
  //添加數據
  addCar = async () => {
    const carName = this.refs.carName.value;
    if (carName.trim().length <= 0) return alert("汽车名不能为空");
    const { data } = await this.$http.post("/addcar", { name: carName });
    if ((data.code = "0")) {
      this.getCarList();
      this.refs.carName.value = "";
    }
  };
  // 删除汽车数据
  deleteCar(id) {
    console.log(id);
    this.$http.post("/delcar", { id }).then(res => {
      if(res.data.code == '0') {
        this.getCarList()
      }else {
        alert('删除失败')
      }
    }).catch((err => {
      console.log(err);
    }));
  }
}
